using System;
using Microsoft.Practices.ObjectBuilder2;

namespace UniAspect.ContainerOverride
{
    public class OverriddenDependencyResolverPolicy : IDependencyResolverPolicy
    {
        public readonly string Name;
        public readonly string ContainerName;
        public readonly Type Type;

        public OverriddenDependencyResolverPolicy(Type type, string name, string container)
        {
            Type = type;
            ContainerName = container;
            Name = name;
        }

        public object Resolve(IBuilderContext context)
        {
            Guard.ArgumentNotNull(context, "context");
            var objectBuildKey = new NamedTypeBuildKey(Type, Name);

            if(string.IsNullOrEmpty(ContainerName))
            {
                IBuilderContext recursiveContext = context.CloneForNewBuild(objectBuildKey, null);
                return recursiveContext.Strategies.ExecuteBuildUp(recursiveContext);
            }

            var overrideKey = new ContainerOverrideKey(ContainerName);
            var policy = context.Policies.Get<IContainerOverridePolicy>(overrideKey);
            if(policy == null || policy.Override == null)
                throw new DependencyMissingException(overrideKey);

            return policy.Override.Resolve(objectBuildKey.Type, objectBuildKey.Name);
        }
    }
}